import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: '/api',
  timeout: 30000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 如果是blob响应（文件下载），直接返回data
    if (response.config.responseType === 'blob') {
      return response.data
    }
    
    const res = response.data
    
    // 根据后端返回的code判断请求是否成功
    if (res.code === '200') {
      return res
    } else {
      ElMessage({
        message: res.message || '请求失败',
        type: 'error',
        duration: 5 * 1000
      })
      
      // 401: 未授权
      if (res.code === '401') {
        const userStore = useUserStore()
        userStore.logout()
        router.push('/login')
      }
      
      return Promise.reject(new Error(res.message || '请求失败'))
    }
  },
  error => {
    console.error('响应错误:', error)
    
    if (error.response?.status === 401) {
      ElMessage({
        message: '登录已过期，请重新登录',
        type: 'error',
        duration: 5 * 1000
      })
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
    } else {
      ElMessage({
        message: error.message || '网络错误',
        type: 'error',
        duration: 5 * 1000
      })
    }
    
    return Promise.reject(error)
  }
)

export default service